<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    :close-func="closeFunc"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './data';

  import { addPostApi, updatePostApi } from '@/api/system/post';
  import type { SystemPostItem } from '@/api/system/model/postModel';

  const isUpdate = ref(true);
  const rowId = ref('');

  const emit = defineEmits(['success', 'register']);

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    const { id } = data;
    rowId.value = id;
    if (id) {
      setFieldsValue({ ...data });
    }
  });

  const getTitle = computed(() => (!unref(rowId) ? '新增分类' : '编辑分类'));

  const closeFunc = async () => {
    await resetFields();
    return true;
  };

  async function handleSubmit() {
    try {
      const values: SystemPostItem = await validate();
      setModalProps({ confirmLoading: true });
      // TODO custom api
      const res = unref(rowId)
        ? await updatePostApi({ ...values, id: rowId.value })
        : await addPostApi(values);
      console.log(res);
      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
